package top.ooyyh.bytheway.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ooyyh.bytheway.entity.User;
import top.ooyyh.bytheway.mapper.PowerMapper;
import top.ooyyh.bytheway.mapper.UserMapper;
import top.ooyyh.bytheway.model.request.CreateUserRequest;
import top.ooyyh.bytheway.model.request.LoginRequest;
import top.ooyyh.bytheway.model.request.RegisterRequest;
import top.ooyyh.bytheway.model.vo.MenuVo;
import top.ooyyh.bytheway.model.vo.UserVo;
import top.ooyyh.bytheway.service.UserService;
import top.ooyyh.bytheway.utils.JwtUtils;
import top.ooyyh.bytheway.utils.Result;

import java.awt.*;
import java.util.*;
import java.util.List;

@Service

public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private PowerMapper powerMapper;

    @Override
    public Result login(LoginRequest loginRequest) {
        // 确保不为空
        if (loginRequest.getUsername() == null || loginRequest.getUsername().trim().isEmpty()) {
            return Result.error(400, "用户名不能为空");
        }
        if (loginRequest.getPassword() == null || loginRequest.getPassword().trim().isEmpty()) {
            return Result.error(400, "密码不能为空");
        }
        User user = userMapper.getUserByName(loginRequest.getUsername());
        if (user == null || !user.getPassword().equals(loginRequest.getPassword())){
            return Result.error(401, "用户名或密码错误");
        } else {
            // 构造tokenClaims
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            String token = JwtUtils.generateToken(claims);
            UserVo userVo = UserVo.fromUser(user);
            userVo.setToken(token);
            Result result = Result.success();
            result.setMsg("登录成功");
            result.setData(userVo);
            return result;
        }
    }

    @Override
    public Result loginWithOutPass(String token) {
        if (token == null || token.trim().isEmpty()){
            return Result.error(400, "token不能为空");
        }
        if (!JwtUtils.validateToken(token)) {
            return Result.error(401, "token无效或已过期");
        } else {
           Claims claims = JwtUtils.parseToken(token);
           return Result.success(claims);
        }
    }

    @Override
    public Result getUserMenu(String token) {
        if (token == null || token.trim().isEmpty()) {
            return Result.error(400, "token不能为空");
        }
        if (!JwtUtils.validateToken(token)) {
            return Result.error(401, "token无效或已过期");
        }

        Claims claims = JwtUtils.parseToken(token);
        String username = (String) claims.get("username");
        List<MenuVo> allMenu = userMapper.getUserAllMenu(username);

        // 构建树形菜单
        List<MenuVo> menuTree = buildMenuTree(allMenu);

        return Result.success(menuTree);
    }
    private List<MenuVo> buildMenuTree(List<MenuVo> menuList) {
        List<MenuVo> rootMenus = new ArrayList<>();
        for (MenuVo menu : menuList) {
            if (menu.getParentId() == 0) {
                rootMenus.add(menu);
            }
        }
        for (MenuVo rootMenu : rootMenus) {
            List<MenuVo> children = getChildren(rootMenu.getId(), menuList);
            rootMenu.setChildren(children);
        }
        return rootMenus;
    }
    private List<MenuVo> getChildren(Integer parentId, List<MenuVo> menuList) {
        List<MenuVo> children = new ArrayList<>();
        for (MenuVo menu : menuList) {
            if (parentId.equals(menu.getParentId())) {
                if (menu.getType().equals("C")){
                    menu.setChildren(getChildren(menu.getId(), menuList));
                    children.add(menu);
                }
                if (menu.getType().equals("M")){
                    children.add(menu);
                }
            }
        }
        return children;
    }
    @Override
    public Result registerByEmail(RegisterRequest registerRequest) {
        // 使用QMail作为源邮箱
        return null;
    }
    @Override
    public Result register(RegisterRequest registerRequest) {
        // 判断用户是否已存在
        if (userMapper.isUserNameExist(registerRequest.getUser().getUsername())){
            return Result.error("用户已存在");
        }
        userMapper.insertUser(registerRequest.getUser());
        powerMapper.grantUserPowerByRole(registerRequest.getUser().getId(),"user");
        return Result.success("注册成功！");
    }
    @Override
    public Result createUser(CreateUserRequest user) {
        if (userMapper.isUserNameExist(user.getUser().getUsername())){
            return Result.error("用户已存在");
        }
        userMapper.insertUser(user.getUser());
        for (String permission : user.getPermissions()) {
            powerMapper.grantUserPower(user.getUser().getId() , permission);
        }
        return Result.success("you got me");
    }

    @Override
    public Result getAllRolePower() {
        List<Map<String, String>> allRolePower = powerMapper.getAllRolePower();
        JSONObject result = new JSONObject();
        for (Map<String, String> row : allRolePower) {
            String role = (String) row.get("role");
            String[] powers = row.get("powers").split(",");
            result.set(role, Arrays.asList(powers));
        }
        return Result.success(result);
    }
}
